package com.gyg.unsafeThreadDemo;

/**
 * 线程不安全情况以：不安全情况下买票
 */
public class NoSafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket, "小A").start();
        new Thread(buyTicket, "小B").start();
        new Thread(buyTicket, "小C").start();
    }
}

/**
 * 买票
 */
class BuyTicket implements Runnable {
    private int ticketNum = 10;
    private boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //synchronized：给方法上锁
    private void buy() throws InterruptedException {
        if (ticketNum <= 0) {
            flag = false;
        } else {
            //放大问题的发生性
            Thread.sleep(100);
            System.out.println(Thread.currentThread().getName() + "买到的票序号为：" + ticketNum--);
        }
    }
}


